package com.imooc.order.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.imooc.order.dataobject.OrderDetail;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.from.Orderfrom;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderFrom2OrderDTO {

    public static OrderDTO conver(Orderfrom orderfrom) throws OrderException {
        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerAddress(orderfrom.getAddress());
        orderDTO.setBuyerName(orderfrom.getName());
        orderDTO.setBuyerOpenid(orderfrom.getOpenid());
        orderDTO.setBuyerPhone(orderfrom.getPhone());

        List<OrderDetail> orderDetails=new ArrayList<>();
        try {
            orderDetails=gson.fromJson(orderfrom.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        } catch (Exception e) {
          log.error("json转化异常"+orderfrom.getItems());
          throw new OrderException(ResultEnum.Param_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;

    }
}
